import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import AliAppPayForm from './PayForm/AliPayAppForm';
import UnionPayAppForm from './PayForm/UnionPayAppForm';
import WxPayAppForm from './PayForm/WxPayAppForm';
import moment from 'moment';
import { connect } from 'dva';
import {
  List,
  Card,
  Drawer, Form, Button, message,
  Avatar, Badge, Switch,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './List.less';


@connect(({ gateway, loading }) => {
  return ({
    gateway,
    loading: loading.models.gateway,
  });
})
class BasicList extends PureComponent {
  state = { visible: false, done: false, submitEditLoading: false };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'gateway/fetch',
    });
  }

  showDrawer = (title, parameters, entryId) => {
    this.setState({
      visible: true,
      title: title,
      parameters: parameters,
      entryId: entryId,
    });
  };

  onClose = () => {
    if (!this.state.submitEditLoading) {
      this.setState({
        visible: false,
      });
    }

  };

  submitEdit = () => {
    this.form.validateFields((errors, result) => {
      if (errors) {
        message.error(errors[Object.keys(errors)[0]].errors[0].message);
      } else {
        this.setState({
          submitEditLoading: true,
        });
        //submit
        const { dispatch } = this.props;
        dispatch({
          type: 'gateway/editPars',
          parameters: result,
          entryId: this.state.entryId,
          success: () => {
            if (this.props.gateway.lastResult.ErrorCode == 0) {
              this.props.gateway.list[this.state.entryId - 1].Parameter = JSON.stringify(result);
              message.success('编辑成功');
              this.setState({
                visible: false,
                submitEditLoading: false,
              });
            } else {
              this.setState({
                visible: true,
                submitEditLoading: false,
              });
            }
          },
        });

      }

    });
  };


  submitEnable(entryId, enable) {
    //submit
    const { dispatch } = this.props;
    dispatch({
      type: 'gateway/editEnable',
      enable: enable,
      entryId: entryId,
      success: () => {
        if (this.props.gateway.lastResult.ErrorCode == 0) {
          this.props.gateway.list[entryId - 1].Enable = enable;
          if (enable) {
            this.props.gateway.list[entryId - 1].Status = 2;
          }else {
            this.props.gateway.list[entryId - 1].Status = 1;
          }
          message.success(enable ? '开通成功' : '停用成功');

        }
      },
    });
  }

  refForm = (obj) => {
    this.form = obj;
  };

  renderStatus(status) {
    //1,等待检查，2，检查通过，3，网关异常，4，运行正常
    const statusConfig = [
      ['等待检查', 'default'],
      ['检查通过', 'processing'],
      ['网关异常', 'error'],
      ['运行正常', 'success'],
    ];
    return <Badge status={statusConfig[status - 1][1]} text={statusConfig[status - 1][0]}/>;
  }

  renderList() {
    const {
      gateway,
      loading,
    } = this.props;
    const list = gateway.list;
    const ListContent = ({ data: { Name, Used, LastActiveTime, Enable, Status, EntryId } }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          <span>应用场景</span>
          <p>{Used}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>最后活动时间</span>
          <p>{Enable ? moment(LastActiveTime).format('YYYY-MM-DD HH:mm') : '无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>运行状态</span>
          <p>
            {this.renderStatus(Status)}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>启用状态</span>
          <p>
            <Switch checkedChildren="已开通" unCheckedChildren="未开通" checked={Enable}
                    onChange={this.submitEnable.bind(this, EntryId, !Enable)}/>
          </p>
        </div>
      </div>
    );
    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="网关列表"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
          >
            <List
              size="large"
              rowKey="id"
              loading={loading}
              dataSource={list}
              renderItem={item => (
                <List.Item
                  actions={[
                    <a
                      onClick={() => {
                        this.showDrawer(item.Name, item.Parameter, item.EntryId);
                      }}
                    >
                      编辑参数
                    </a>,
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar src={item.IcoUrl} shape="square" size="large"/>}
                    title='支付网关名称'
                    description={item.Name}
                  />
                  <ListContent data={item}/>
                </List.Item>
              )}
            />
          </Card>
        </div>
      </PageHeaderWrapper>
    );
  }

  renderDrawer() {
    const editForms = [AliAppPayForm, WxPayAppForm, UnionPayAppForm];
    const EditForm = editForms[this.state.entryId - 1];
    return (
      <Drawer
        title={this.state.title}
        width={420}
        onClose={this.onClose}
        visible={this.state.visible}
        maskClosable={false}
        style={{
          overflow: 'auto',
          height: 'calc(100% - 108px)',
          paddingBottom: '108px',
        }}
      >
        <EditForm parameters={this.state.parameters} ref={this.refForm.bind(this)}/>
        <div
          style={{
            position: 'absolute',
            left: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.onClose.bind(this)} style={{ marginRight: 8 }} loading={this.state.submitEditLoading}>
            取消
          </Button>
          <Button onClick={this.submitEdit.bind(this)} type="primary" loading={this.state.submitEditLoading}>
            确认
          </Button>
        </div>
      </Drawer>
    );

  }

  render() {
    return (<div>
      {this.renderDrawer()}
      {this.renderList()}
    </div>);
  }
}

export default BasicList;
